package com.example.bookshelf;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

//import android.support.v7.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;

import com.example.bookshelf.data.BookItem;
import com.example.bookshelf.data.BookLabel;
import com.example.bookshelf.data.BookManager;
import com.example.bookshelf.data.Bookshelf;

import java.util.ArrayList;
import java.util.Objects;

public class EditActivity extends AppCompatActivity {

    public static final int RESULT_CODE_SUCCESS = 1;
    public static final int RESULT_CODE_FALSE = 0;
    public static final int MODE_ADD = 0;
    public static final int MODE_EDIT = 1;

    private ArrayList<BookLabel> bookLabels;
    private ArrayList<Bookshelf> bookshelves;
    BookItem bookItem;
    private Spinner spinnerBookshelf;
    private Toolbar toolbar;
    private int model;
    private Spinner spinnerReadingState;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_input_book_item);
        Intent intent =getIntent();
        Bundle bundle = intent.getExtras();
        bookLabels = bundle.getParcelableArrayList("bookLabels");
        bookshelves = bundle.getParcelableArrayList("bookshelves");
        model = bundle.getInt("mode");
        Log.v("mode", String.valueOf(model));
        if (MODE_EDIT == model) {
            bookItem = bundle.getParcelable("bookItem");
            initViews();
        }
        else if (MODE_ADD == model){
            bookItem = new BookItem();
        }



        initSpinnerBookShelf();                 // bookshelf的spinner的初始化
        initEditTextLabel();                    // book label的editView的初始化
        initSpinnerReadingState();


        toolbar = findViewById(R.id.toolbar_input);
        setSupportActionBar(toolbar);
        Objects.requireNonNull(getSupportActionBar()).setDisplayShowTitleEnabled(false);
        toolbar.setTitle("编辑书籍信息");
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder dlg = new AlertDialog.Builder(EditActivity.this);
                dlg.setTitle("放弃编辑书籍信息");
                dlg.setPositiveButton("放弃", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        setResult(RESULT_CODE_FALSE);
                        EditActivity.this.finish();
                    }
                });
                dlg.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                    }
                });
                dlg.show();
            }
        });



//        Button button_test = findViewById(R.id.button_test);
//        button_test.setOnClickListener(view -> {
//            goBack();
//            Intent intent = new Intent();
//            Bundle bundle = new Bundle();
//
//            EditText editTextTile = findViewById(R.id.editText_input_title);
//            EditText editTextAuthor = findViewById(R.id.editText_input_author);
//            EditText editTextTranslator = findViewById(R.id.editText_input_translator);
//            EditText editTextPress = findViewById(R.id.editText_input_press);
//            EditText editTextPublishedYear = findViewById(R.id.editText_input_published_year);
//            EditText editTextPublishedMonth = findViewById(R.id.editText_input_published_month);
//            EditText editTextISBN = findViewById(R.id.editText_input_ISBN);
//
//            Spinner spinnerReadingState = findViewById(R.id.spinner_input_reading_state);
////            Spinner spinnerBookshelf = findViewById(R.id.spinner__input_bookshelf);
//
//            EditText editTextNotes = findViewById(R.id.editText_input_notes);
//            EditText editTextLabel = findViewById(R.id.editText_input_label);
//            EditText editTextURL = findViewById(R.id.editText_input_url);
//
//            // 基本信息
//            BookItem bookItem = new BookItem();
//            bookItem.setTitle(editTextTile.getText().toString());
//            bookItem.setAuthor(editTextAuthor.getText().toString());
//            bookItem.setTranslator(editTextTranslator.getText().toString());
//            bookItem.setPress(editTextPress.getText().toString());
//            // 日期
//            String publishedYear = editTextPublishedYear.getText().toString();
//            if (publishedYear.equals(""))
//                bookItem.setPublishedYear(0);
//            else
//                bookItem.setPublishedYear(Integer.parseInt(publishedYear));
//            String publishedMonth = editTextPublishedMonth.getText().toString();
//            if (publishedMonth.equals(""))
//                bookItem.setPublishedMonth(0);
//            else bookItem.setPublishedMonth(Integer.parseInt(publishedMonth));
//            // ISBN
//            bookItem.setISBN(editTextISBN.getText().toString());
//
//            bookItem.setReadingStatus(spinnerReadingState.getSelectedItem().toString());
//            bookItem.setNotes(editTextNotes.getText().toString());
//            bookItem.setUrl(editTextURL.getText().toString());
//            bundle.putParcelable("bookItem", bookItem);
//            intent.putExtras(bundle);
//            setResult(RESULT_CODE_SUCCESS, intent);


//            bundle.putString("translator", editTextTranslator.getText().toString());
//            bundle.putString("press", editTextPress.getText().toString());
//            bundle.putString("publishedYear", editTextPublishedYear.getText().toString());
//            bundle.putString("publishedMonth", editTextPublishedMonth.getText().toString());
//            bundle.putString("ISBN", editTextISBN.getText().toString());
//
//            bundle.putString("notes", editTextNotes.getText().toString());
//            bundle.putString("label", editTextLabel.getText().toString());
//            bundle.putString("url", editTextURL.getText().toString());
//
//            intent.putExtras(bundle);
//            setResult(RESULT_CODE_SUCCESS, intent);


//            InputBookItemActivity.this.finish();
//        });
    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_input_toolbar, menu);
        return true;
    }

    int yourChoice;
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);
        if (item.getItemId() == R.id.item_input_toolbar_save) {
            EditText editTextTile = findViewById(R.id.editText_input_title);
            if (editTextTile.getText().toString().equals("")) {
                AlertDialog.Builder dlg = new AlertDialog.Builder(EditActivity.this);
                dlg.setTitle("未设置标题");
                dlg.setNegativeButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                });
                dlg.show();
            }
            else {
                goBack();
            }

        }

        return true;
    }


    private void goBack(){
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        ImageView imageViewBookCover = findViewById(R.id.imageView_input_book_cover);
        EditText editTextTile = findViewById(R.id.editText_input_title);
        EditText editTextAuthor = findViewById(R.id.editText_input_author);
        EditText editTextTranslator = findViewById(R.id.editText_input_translator);
        EditText editTextPress = findViewById(R.id.editText_input_press);
        EditText editTextPublishedYear = findViewById(R.id.editText_input_published_year);
        EditText editTextPublishedMonth = findViewById(R.id.editText_input_published_month);
        EditText editTextISBN = findViewById(R.id.editText_input_ISBN);
        spinnerReadingState = findViewById(R.id.spinner_input_reading_state);
        Spinner spinnerBookshelf = findViewById(R.id.spinner_input_bookshelf);
        EditText editTextNotes = findViewById(R.id.editText_input_notes);
        EditText editTextLabel = findViewById(R.id.editText_input_label);
        EditText editTextURL = findViewById(R.id.editText_input_url);

        if (editTextTile.getText().toString().equals("")) {

        }

        // 基本信息
//        bookItem.setImageID(imageViewBookCover);
        bookItem.setTitle(editTextTile.getText().toString());
        bookItem.setAuthor(editTextAuthor.getText().toString());
        bookItem.setTranslator(editTextTranslator.getText().toString());
        bookItem.setPress(editTextPress.getText().toString());
        // 日期
        String publishedYear = editTextPublishedYear.getText().toString();
        if (publishedYear.equals(""))
            bookItem.setPublishedYear(0);
        else
            bookItem.setPublishedYear(Integer.parseInt(publishedYear));
        String publishedMonth = editTextPublishedMonth.getText().toString();
        if (publishedMonth.equals(""))
            bookItem.setPublishedMonth(0);
        else bookItem.setPublishedMonth(Integer.parseInt(publishedMonth));
        // ISBN
        bookItem.setISBN(editTextISBN.getText().toString());


        bookItem.setReadingStatus(spinnerReadingState.getSelectedItem().toString());

        String bookshelfName = spinnerBookshelf.getSelectedItem().toString().trim();
        if (!bookshelfName.equals("暂不设置书架")) {
//            bookshelfAdd = new Bookshelf(bookshelfName);
            bookItem.setBookshelfName(bookshelfName);
        }

        String bookLabels = editTextLabel.getText().toString();
        bookItem.setLabels(bookLabels);

        bookItem.setNotes(editTextNotes.getText().toString());
        bookItem.setUrl(editTextURL.getText().toString());


        this.bookshelves.remove(0);
        this.bookshelves.remove(0);


        bundle.putParcelable("bookItem", bookItem);
        bundle.putParcelableArrayList("bookshelves", this.bookshelves);
        bundle.putParcelableArrayList("bookLabels", this.bookLabels);
        intent.putExtras(bundle);

        setResult(RESULT_CODE_SUCCESS, intent);


        EditActivity.this.finish();
    }


    private void initSpinnerBookShelf() {
        bookshelves.add(0, new Bookshelf("默认书架"));
        bookshelves.add(1, new Bookshelf("添加新的书架"));

        spinnerBookshelf = findViewById(R.id.spinner_input_bookshelf);
        ArrayAdapter<Bookshelf> arrayAdapterLabel = new ArrayAdapter<Bookshelf>(
                this, R.layout.item_spinner, bookshelves);
        arrayAdapterLabel.setDropDownViewResource(R.layout.item_spinner_drow_down);
        spinnerBookshelf.setAdapter(arrayAdapterLabel);

        spinnerBookshelf.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                Bookshelf selectedItem = (Bookshelf) spinnerBookshelf.getSelectedItem();
                if (selectedItem.getName().equals("添加新的书架")) {
                    final EditText editText = new EditText(EditActivity.this);
                    AlertDialog.Builder inputDialog =
                            new AlertDialog.Builder(EditActivity.this);
                    inputDialog.setTitle("请输入新书架的名字").setView(editText);
                    inputDialog.setPositiveButton("确定",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    String name = editText.getText().toString();
                                    Log.v("click", "Input ability: 确认按钮-" + name);

                                    if (!name.equals("name") && !name.equals("")) {
                                        boolean isAdd = BookManager.addBookshelf(bookshelves, new Bookshelf(name));
//                                        bookshelves.add(new Bookshelf(name));
                                        if (isAdd) {
                                            spinnerBookshelf.setSelection(bookshelves.size() - 1);
                                            arrayAdapterLabel.notifyDataSetChanged();
                                        }
                                    }
                                    else {
                                        spinnerBookshelf.setSelection(0);
                                        arrayAdapterLabel.notifyDataSetChanged();
                                    }
//                                    Toast.makeText(InputBookItemActivity.this,
//                                            editText.getText().toString(),
//                                            Toast.LENGTH_LONG).show();
//                                    Log.i("666", "onClick: ");
                                }
                            }).show();
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        if (MODE_EDIT == model) {
            int positionSelection = BookManager.getBookshelfPosition(bookshelves, bookItem);
            if (positionSelection>0 && positionSelection<bookshelves.size())
                spinnerBookshelf.setSelection(positionSelection);
        }

    }


    ArrayList<Integer> bookLabelChoices = new ArrayList<>();
    private void initEditTextLabel() {
        EditText editTextLabel = findViewById(R.id.editText_input_label);
        editTextLabel.setFocusable(false);
        editTextLabel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                // 获得数组数据
                final String[] items = new String[bookLabels.size()];
                final boolean[] initChoiceSets = new boolean[bookLabels.size()];

                for (int i=0; i<bookLabels.size(); i++) {
                    items[i] = bookLabels.get(i).toString();
                    initChoiceSets[i] = false;
                }

                final EditText editText = new EditText(EditActivity.this);
                AlertDialog.Builder inputDialog =
                        new AlertDialog.Builder(EditActivity.this);


                // 设置多选对话框----------------------------------------------------------------------
                bookLabelChoices.clear();
                AlertDialog.Builder multiChoiceDialog =
                        new AlertDialog.Builder(EditActivity.this);
                multiChoiceDialog.setTitle("请选择标签");
                multiChoiceDialog.setMultiChoiceItems(items, initChoiceSets,
                        new DialogInterface.OnMultiChoiceClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which,
                                                boolean isChecked) {
                                if (isChecked) {
                                    bookLabelChoices.add(which);
                                } else {
                                    bookLabelChoices.remove(Integer.valueOf(which));
                                }
                            }
                        });
                multiChoiceDialog.setPositiveButton("确定",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                int size = bookLabelChoices.size();
                                StringBuilder str = new StringBuilder();
                                for (int i = 0; i < size; i++) {
                                    str.append(items[bookLabelChoices.get(i)]).append("，");
                                }
                                EditText editTextLabel = findViewById(R.id.editText_input_label);
                                editTextLabel.setText(str);
                            }
                        });
                multiChoiceDialog.setNegativeButton("添加新的标签",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                inputDialog.show();
                            }
                        });
                multiChoiceDialog.show();


                // 设置添加标签的对话框-----------------------------------------------------------------
                inputDialog.setTitle("请输入新标签的名字").setView(editText);
                inputDialog.setPositiveButton("确定",
                        (dialog, which) -> {
                            String name = editText.getText().toString();
                            if (!name.equals("name")) {
                                BookManager.addBookLabel(bookLabels, new BookLabel(name));
                            }
                        });
                inputDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialogInterface) {
//                        singleChoiceDialog.show();
                    }
                });
            }
        });

        if (MODE_EDIT == model) {
            editTextLabel.setText(bookItem.getLabels());
        }

    }


    private void initSpinnerReadingState() {
        spinnerReadingState = findViewById(R.id.spinner_input_reading_state);
        if (MODE_EDIT == model) {
            int readingStateSelect = BookManager.getReadingStatePosition(bookItem);
            if (0 != readingStateSelect) {
                spinnerReadingState.setSelection(readingStateSelect);
            }
        }
    }


    private void initViews() {
        ImageView imageViewBookCover = findViewById(R.id.imageView_input_book_cover);
        EditText editTextTile = findViewById(R.id.editText_input_title);
        EditText editTextAuthor = findViewById(R.id.editText_input_author);
        EditText editTextTranslator = findViewById(R.id.editText_input_translator);
        EditText editTextPress = findViewById(R.id.editText_input_press);
        EditText editTextPublishedYear = findViewById(R.id.editText_input_published_year);
        EditText editTextPublishedMonth = findViewById(R.id.editText_input_published_month);
        EditText editTextISBN = findViewById(R.id.editText_input_ISBN);
        Spinner spinnerReadingState = findViewById(R.id.spinner_input_reading_state);
        Spinner spinnerBookshelf = findViewById(R.id.spinner_input_bookshelf);
        EditText editTextNotes = findViewById(R.id.editText_input_notes);
        EditText editTextLabel = findViewById(R.id.editText_input_label);
        EditText editTextURL = findViewById(R.id.editText_input_url);

//        imageViewBookCover.setImageResource(bookItem.getImageID());
        editTextTile.setText(bookItem.getTitle());
        editTextAuthor.setText(bookItem.getAuthor());
        editTextTranslator.setText(bookItem.getTranslator());
        editTextPress.setText(bookItem.getPress());
//        editTextPublishedYear.setText();

        editTextISBN.setText(bookItem.getISBN());
        editTextNotes.setText(bookItem.getNotes());
        editTextURL.setText(bookItem.getUrl());



    }

}